<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>异步迭代器</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    let t = (time = 1, ok = true) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (ok) {
            resolve(time);
          } else {
            reject("出现错误了");
          };
        }, time * 1000);
      });
    };

    // 普通的 for of 遍历时，无法按顺序获取得到结果
    function t1() {
      let arr = [t(2), t(1), t(3)];
      for (let item of arr) {
        item.then(res => {
          console.log(res);
        });
      };
    };

    // t1();

    // 使用异步迭代器，可以得到顺序结果。
    async function t2() {
      let arr = [t(2), t(1), t(3)];
      for await (let item of arr) {
        console.log(item);
      };
    };

    t2();
  };
</script>

</html>